import "./assets/style.css"
import InitMap from "./components/initmap/initmap"
import PrintMap from "./components/print/print"
import Routing from "./components/routing/routing"
import { Image as ImageLayer, Tile as TileLayer } from "ol/layer"
import { ImageArcGISRest, OSM, ImageWMS } from "ol/source"
import { toLonLat, transform } from "ol/proj"
import { getUrlParams } from "./utils/utils"
import EventEmitter2 from "eventemitter2"

let map
const emitter = new EventEmitter2()
window.emitter = emitter
initApp()

function initApp() {
  let el = mapOpt.el || 'map'
  mapOpt.defaultMap = defaultMap
  window.map = map = new InitMap(el, mapOpt)

  map.on("click", (evt) => {
    let coor = toLonLat(evt.coordinate)
    console.log(coor)
    emitter.emit("map-click", evt)
  })

  const closer = document.getElementById("popup-closer")
  closer.addEventListener("click", (evt) => {
    closer.blur()
    emitter.emit("popup-close")
    return false
  })

  // initPrint()
  initRouting()
}

function initPrint() {
  const printBtn = document.getElementById("export-png")
  printBtn.addEventListener("click", function () {
    map.once("rendercomplete", function () {
      new PrintMap(map)
    })
    map.renderSync()
  })
}

function initRouting() {
  const routing = new Routing(map)

  // 岛屿影像服务
  const imageLayer = new ImageLayer({
    source: new ImageArcGISRest({
      ratio: 1,
      params: {},
      url: imageUrl,
    }),
  })
  map.addLayer(imageLayer)

  // 岛屿名称
  const wms = new ImageLayer({
    source: new ImageWMS({
      url: serverUrl,
      params: { LAYERS: islandServe.layers },
      ratio: 1,
      serverType: "geoserver",
    }),
  })
  map.addLayer(wms)

  let params = getUrlParams()
  let id = params.id
  $.ajax({
    url: apiRoute,
    type: "post",
    dataType: "json",
    contentType:'application/json',
    data: JSON.stringify({
      id: id,
    }),
  }).then((json) => {
    let data = json.data
    routing.draw_route(data)
  }).catch((err)=>{
    console.log(err)
  })
  // const json ='{"code":1,"msg":"成功","data":{"routeArr":[{"routename":"心脏病","wkt":"LINESTRING(25.44 123.28 4,16.02 111.45 1,25.44 123.28 3,16.01 112.298 2)"}],"id":"6","name":"浪花礁"}}'

  $.ajax({
    url: apiHospital,
    type: "post",
    dataType: "json",
    contentType:'application/json',
    data: JSON.stringify({
      id: id,
    }),
  }).then((res) => {
    // console.log(res)
    const dataHospital = res.data
    routing.draw_poi(dataHospital)
  }).catch((err)=>{
    console.log(err)
  })
  // const json1 = '{"code": "1", "msg": "成功", "data":[{"hospLevel":"test","hospName":"test","hospPosition":"test","id":1,"speciality":"test"},{"hospLevel":"t1","hospName":"t1","hospPosition":"t1","id":4,"speciality":"t1"}]}';
}
